#include "common.h"
#include "gprogram.h"
#include "glwindow.h"

CGProgram::CGProgram()
{
	pProgram = NULL;
	pVertexShader = NULL;
	pFragmentShader = NULL;
}

CGProgram::~CGProgram(void)
{
	if (!pProgram)
		glDeleteObjectARB(pProgram);
	if (!pVertexShader)
		delete pFragmentShader;
	if (!pFragmentShader)
		delete pFragmentShader;
}

bool CGProgram::Create(const std::string& szProgram, program_type nProgram)
{
	pProgram = glCreateProgramObjectARB();

	if (nProgram == vertex_only || nProgram == vertex_and_fragment)
	{
		pVertexShader = new CGShader(vertex_shader);
		pVertexShader->LoadFromFile(std::string(szProgram + std::string(".vert")).c_str());
		pVertexShader->CompileLink(pProgram);
	}

	if (nProgram == fragment_only || nProgram == vertex_and_fragment)
	{
		pFragmentShader = new CGShader(fragment_shader);
		pFragmentShader->LoadFromFile(std::string(szProgram + std::string(".frag")).c_str());
		pFragmentShader->CompileLink(pProgram);
	}

	glLinkProgramARB(pProgram);

	GLint progLinkSuccess;
	glGetObjectParameterivARB(pProgram, GL_OBJECT_LINK_STATUS_ARB, &progLinkSuccess);
	if (!progLinkSuccess)
	{
		std::string szOut = std::string("Shader ") + szProgram + std::string(" could not be linked");
		MessageBox(NULL, szOut.c_str(), "Error", MB_OK);
		printInfoLog(pProgram);
		return false;
	}
	return true;
}

void CGProgram::On()
{
	glUseProgramObjectARB(pProgram);
}

void CGProgram::Off()
{
	glUseProgramObjectARB(0);
}
